﻿using System.Collections.Concurrent;
using Microsoft.Extensions.DependencyInjection;

namespace DeviceCommons.DeviceMessages.Factories
{
    /// <summary>
    /// 状态工厂注册中心（DI实例版本）
    /// </summary>
    public class StateFactoryRegistryService : IStateFactoryRegistry
    {
        private readonly ConcurrentDictionary<byte, Func<IStateFactory>> _factoryCreators = new();
        private readonly ConcurrentDictionary<byte, IStateFactory> _factoryCache = new();
        private readonly IStateFactory _defaultFactory;
        private readonly IServiceProvider? _serviceProvider;

        /// <summary>
        /// 构造函数（用于DI）
        /// </summary>
        /// <param name="serviceProvider">服务提供者</param>
        /// <param name="defaultFactory">默认工厂</param>
        public StateFactoryRegistryService(IServiceProvider? serviceProvider = null, IStateFactory? defaultFactory = null)
        {
            _serviceProvider = serviceProvider;
            _defaultFactory = defaultFactory ?? new DefaultStateFactory();
        }

        /// <summary>
        /// 注册状态工厂
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="factoryCreator">工厂创建器</param>
        public void RegisterFactory(byte deviceType, Func<IStateFactory> factoryCreator)
        {
            _factoryCreators[deviceType] = factoryCreator;
            // 清除缓存以确保下次获取时使用新的工厂
            _factoryCache.TryRemove(deviceType, out _);
        }

        /// <summary>
        /// 获取状态工厂
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>状态工厂实例</returns>
        public IStateFactory GetFactory(byte deviceType)
        {
            if (_factoryCache.TryGetValue(deviceType, out var cachedFactory))
                return cachedFactory;

            if (_factoryCreators.TryGetValue(deviceType, out var creator))
            {
                var factory = creator();
                _factoryCache[deviceType] = factory;
                return factory;
            }

            // 尝试从服务提供者获取注册的工厂
            if (_serviceProvider != null)
            {
                var registrations = _serviceProvider.GetServices<StateFactoryRegistration>();
                var registration = registrations.FirstOrDefault(r => r.DeviceType == deviceType);
                if (registration != null)
                {
                    var factory = (IStateFactory)_serviceProvider.GetRequiredService(registration.FactoryType);
                    _factoryCache[deviceType] = factory;
                    return factory;
                }
            }

            return _defaultFactory;
        }

        /// <summary>
        /// 清空工厂缓存
        /// </summary>
        public void ClearCache()
        {
            _factoryCache.Clear();
        }

        /// <summary>
        /// 检查是否已注册指定设备类型的工厂
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>是否已注册</returns>
        public bool IsRegistered(byte deviceType)
        {
            if (_factoryCreators.ContainsKey(deviceType))
                return true;

            if (_serviceProvider != null)
            {
                var registrations = _serviceProvider.GetServices<StateFactoryRegistration>();
                return registrations.Any(r => r.DeviceType == deviceType);
            }

            return false;
        }
    }

    /// <summary>
    /// 状态工厂注册中心（静态版本，向后兼容）
    /// </summary>
    public static class StateFactoryRegistry
    {
        private static readonly ConcurrentDictionary<byte, Func<IStateFactory>> _staticFactoryCreators = new();
        private static readonly ConcurrentDictionary<byte, IStateFactory> _staticFactoryCache = new();
        private static readonly IStateFactory _staticDefaultFactory = new DefaultStateFactory();

        /// <summary>
        /// 注册状态工厂（向后兼容）
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="factoryCreator">工厂创建器</param>
        public static void RegisterFactory(byte deviceType, Func<IStateFactory> factoryCreator)
        {
            _staticFactoryCreators[deviceType] = factoryCreator;
            _staticFactoryCache.TryRemove(deviceType, out _);
        }

        /// <summary>
        /// 获取状态工厂（向后兼容）
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>状态工厂实例</returns>
        public static IStateFactory GetFactory(byte deviceType)
        {
            if (_staticFactoryCache.TryGetValue(deviceType, out var cachedFactory))
                return cachedFactory;

            if (_staticFactoryCreators.TryGetValue(deviceType, out var creator))
            {
                var factory = creator();
                _staticFactoryCache[deviceType] = factory;
                return factory;
            }

            return _staticDefaultFactory;
        }
    }
}
